import 'package:get/get.dart';
import 'package:oramemo/core/controllers/device_controller.dart';
import 'package:oramemo/core/repositories/default_api.dart';
import 'package:oramemo/entity/user_task_query_entity.dart';
import 'package:oramemo/entity/user_task_query_entity.dart';
import 'package:oramemo/entity/user_task_query_entity.dart';
import 'package:oramemo/pages/transcription/ai_transcription/ai_transcription_logic.dart';

/// 事件数据模型
class EventModel {
  final String title;
  final String startTime;
  final String taskDetail;
  final bool isCompleted;

  EventModel({
    required this.title,
    required this.startTime,
    required this.taskDetail,
    this.isCompleted = false,
  });
}

/// 事件页面控制器
class EventLogic extends GetxController {
  // 事件列表
  final RxList<EventModel> events = <EventModel>[].obs;

  final AiTranscriptionLogic aiTranscriptionLogic =
      Get.find<AiTranscriptionLogic>();

  @override
  void onInit() {
    onLoad();
    super.onInit();
  }

  Future<void> onLoad() async {
    await requestDevices();
    requestData(page: 1);
  }

  Future<void> requestDevices() async {
    await aiTranscriptionLogic.deviceController.fetchDevices();
    if (aiTranscriptionLogic.deviceController.devices.isNotEmpty) {
      aiTranscriptionLogic.state.data =
          aiTranscriptionLogic.deviceController.devices[0];
    }
    update();
  }

  requestData({required int page}) async {
    UserTaskQueryEntity? res =
        await DefaultApi().oraUserTaskQueryGet<UserTaskQueryEntity>();
    events.clear();
    if (res?.rows?.isNotEmpty == true) {
      // 加载测试数据
      for (int i = 0; i < res!.rows!.length; i++)
        events.add(
          EventModel(
            title: res.rows![i].taskTitle ?? '未命名事项',
            startTime: res.rows![i].taskTime ?? '未知时间',
            taskDetail: res.rows![i].taskDesc ?? '完成日常任务',
          ),
        );
    }
    update();
  }

  /// 添加新事件
  void addEvent(EventModel event) {
    events.add(event);
  }

  /// 删除事件
  void removeEvent(int index) {
    if (index >= 0 && index < events.length) {
      events.removeAt(index);
    }
  }

  /// 更新事件状态
  void toggleEventStatus(int index) {
    if (index >= 0 && index < events.length) {
      final event = events[index];
      events[index] = EventModel(
        title: event.title,
        startTime: event.startTime,
        taskDetail: event.taskDetail,
        isCompleted: !event.isCompleted,
      );
    }
  }
}
